<?php

class WXService
{

    const  Get_Token_Url = 'https://api.weixin.qq.com/cgi-bin/token';
    const  Get_UserInfo_Url = 'https://api.weixin.qq.com/cgi-bin/user/info';
    const  Get_SendMessage_Url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
    const  Get_GetAccessToken_Url = 'https://api.weixin.qq.com/sns/oauth2/access_token';

    const Get_Address_Url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';

    const deliever_url = "https://api.weixin.qq.com/pay/delivernotify?access_token=";

    const create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";





    const shopsecret = "weixin374";

    /*
    * 获取微信token
    *
    */
    public static function getWXToken ($wx_id)
    {

        //获取列表
        $searchsql = Util::initSearchSql();

        $searchsql = Util::getSerarchStrAdd($searchsql,"wx_id",$wx_id);

        $searchsql = $searchsql." and Expire_Time >= '".DateUtil::getNowTime()."'";

        //排序
        $searchsql = $searchsql . " order by create_time  desc";

        $list = WxTokenlist::model()->findAll($searchsql);


        if(count($list) >0)
            return $list[0];

        else
        {
            //调用接口 获取 token

            $wx_info = WXService::getWeixinInfo($wx_id);

            $url = WXService::Get_Token_Url."?grant_type=client_credential&appid=".$wx_info->AppID."&secret=".$wx_info->AppSecret;


            $data = Yii::app()->CURL->run( $url ,FALSE,
                json_encode(array(
                    'appid'=>$wx_info->AppID,
                    'secret'=>$wx_info->AppSecret
                )),TRUE
                ,TRUE);

            $data = json_decode($data);



            //return "-1";
            $access_token = $data->access_token;
            //var_dump($data);

            //echo  "token   ".$access_token;

            if(	array_key_exists('access_token',  $data) )
            {
                $access_token = $data->access_token;

                $expire_seconds = $data->expires_in;

                $current_time = DateUtil::GetCurrentUTCDateTime();

                $expire_date =gmdate('Y-m-d H:i:s',time()+3600*8+$expire_seconds);

                //insert

                $obj = new WxTokenlist();
                Util::initObjDataInfo($obj);


                $obj->Token_Num = $access_token;
                $obj->Is_Active = 1;
                $obj->Expire_Time = $expire_date;
                $obj->wx_id = $wx_id;


                Util::saveObjData($obj);

                return $obj;



            }

            throw new Exception("token 获取失败");
        }



    }


    /*
    *
    * 获取微信信息
    */
    public static function getWeixinInfo ($wx_id)
    {
        $wx_info = WxWeixininfo::model()->findByPK($wx_id);
        Util::checkExistAndNotDelete($wx_info);

        return $wx_info;



    }


    /*
    *  获取微信用户信息
    *
    */
    public static function getWXUserinfo ($wx_id,$open_id)
    {
        $token = WXService::getWXToken($wx_id)->Token_Num;


        $url = WXService::Get_UserInfo_Url."?access_token=".$token."&openid=".$open_id."&lang=zh_CN";
        // echo $url;


        $data = Yii::app()->CURL->run( $url ,FALSE,
            json_encode(array(

            )),TRUE
            ,TRUE);

        $data = json_decode($data);

       // print_r($data);

        //insert
        if(isset($data->openid) == false || isset($data->nickname) == false)
        {
            $msg = "获取用户信息失败 ".$open_id;
            Util::log_outptut($msg);

            throw new Exception($msg);


            return;

        }




        $nickname = $data->nickname;
        $sex = $data->sex;
        $province = $data->province;
        $city = $data->city;
        $country = $data->country;
        $headimgurl = $data->headimgurl;
        $subscribe_time = $data->subscribe_time;
        $subscribe = $data->subscribe;
        $remark = $data->remark;
        $group_id = $data->groupid;
        $tagid_list=  $data->tagid_list;
        $tag_str = "";

        for($i=0;$i<count($tagid_list);$i++)
        {
            $tagid = $tagid_list[$i];
            if($i == 0)
                $tag_str = $tagid;
            else
                $tag_str = $tag_str.",".$tagid;
        }

        //echo "data ready";


       // $s_time = CommonAdmin::unixtime_to_date($subscribe_time,8);

        date_default_timezone_set ('Asia/Shanghai');
        $time = $subscribe_time + 8 * 3600;
        $datetime = new DateTime("@$time");
        $s_time = $datetime->format("Y-m-d H:i:s");

        //insert

         $user  = WxUser::model()->find("Weixin_ID=:Weixin_ID ",
                     array(":Weixin_ID" => $open_id));

        if(empty($user))
        {
            //echo "new data";

            $user = new WxUser();
            Util::initObjDataInfo($user);


        }





        $user->Weixin_Name = $nickname;
        $user->wx_id = $wx_id;
        $user->Weixin_ID = $open_id;
        $user->Is_Active = 1;
        $user->Weixin_Sex = $sex;
        $user->Weixin_City = $city;
        $user->Weixin_Province = $province;
        $user->Weixin_Country = $country;
        $user->Weixin_Avatar = $headimgurl;
       $user->Subscribe_Time = $s_time;
        $user->subscribe = $subscribe;
        $user->Remark = $remark;
        $user->group_id = $group_id;
        $user->taglist = $tag_str;


        //echo "sava data";

        Util::saveObjData($user);





        return $user;


    }

    /*
    *
    * 设置菜单
    */
    public static function updateMenuinfo($wx_id)
    {
        //获取token
        $token = WXService::getWXToken($wx_id)->Token_Num;

        //获取菜单列表

        $menulist= WXService::getMenuList($wx_id);

        //菜单string
        $finalarray = WXService::getmenustrByMenulist($menulist);



        $url = WXService::create_menu_url.$token;







        $data = Yii::app()->CURL->run($url ,FALSE,
            urldecode(json_encode($finalarray)),TRUE
            ,TRUE);

        $data = json_decode($data);

        if($data->errcode == 0)
        {
            return $menulist;
        }
        else
        {
            throw new Exception($data->errmsg);
        }









    }


    /*
    * 获取菜单列表
    *
    */
    public static function getmenustrByMenulist($menulist)
    {

        $menuarray = array();


        for($i=0;$i<count($menulist);$i++)
        {
            $menuinfo = $menulist[$i];


            //一级
            $btn_1_1 = array();
            $btn_1_1["name"] = urlencode($menuinfo->name);

            if($menuinfo->type != null)
            {
                $btn_1_1["type"] = $menuinfo->type;

                if($menuinfo->type == "view")
                {
                    $btn_1_1["url"] = $menuinfo->url;

                }

                if($menuinfo->type == "click")
                {
                    $btn_1_1["key"] = $menuinfo->key;

                }


            }

            //二级

            if(count($menuinfo->childlist) >0)
            {
                $subinfo = array();

                //循环

                for($j=0;$j<count($menuinfo->childlist);$j++)
                {
                    $submenu = $menuinfo->childlist[$j];

                    $btn_2 = array();
                    $btn_2["name"] = urlencode($submenu->name);

                    if($submenu->type != null)
                    {
                        $btn_2["type"] = $submenu->type;

                        if($submenu->type == "view")
                        {
                            $btn_2["url"] = $submenu->url;

                        }

                        if($submenu->type == "click")
                        {
                            $btn_2["key"] = $submenu->key;

                        }


                    }

                    array_push($subinfo,$btn_2);

                }


                $btn_1_1["sub_button"] =$subinfo;

            }


            //add


            array_push($menuarray,$btn_1_1);


        }


        $finalarray["button"]= $menuarray;


        return $finalarray;






    }

    /*
    *  获取菜单列表
    *
    */
    public static function getMenuList($wx_id)
    {


        //leve 1
         $levellist  = WxMenu::model()->findAll("is_delete =0 and wx_id=:wx_id and level = 1 order by sort asc ",
                     array(":wx_id" => $wx_id));



        for($i=0;$i<count($levellist);$i++)
        {
            $menuinfo = $levellist[$i];

            $slevellist  = WxMenu::model()->findAll(" is_delete =0 and p_id=:p_id and level = 2 order by sort asc ",
                array(":p_id" => $menuinfo->id));

            if(count($slevellist) > 0 )
            $menuinfo->childlist = $slevellist;


        }


       // echo($levellist);


        return  $levellist;

    }







}


?>